#coding:utf-8

import os, sys
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEAudio import MIMEAudio
from email.MIMEMessage import MIMEMessage
import smtplib


class EmailMessage(object):
    content_type = 'plain'
    def __init__(self, subject, body, from_email, to=None, bcc=None):
        self.to = to or []
        self.bcc = bcc or []
        self.from_email = from_email
        self.subject = subject
        self.body = body
        self.attachments = []
    
    @property
    def message(self):
        msg = MIMEMultipart('related')
        body_msg = MIMEText(self.body, self.content_type)
        msg.attach(body_msg)
        for name, content, mimetype in self.attachments:
            #msg_file.add_header('Content-Type', ftype, name=fname)
            #msg_file.add_header('Content-Disposition', 'attachment', filename=fname)
            #self.root_msg.attach(msg_file)
            attach_msg = self.mimeobject(mimetype)(content)
            attach_msg.add_header('Content-Type', mimetype, name=name)
            attach_msg.add_header('Content-Disposition', 'attachment', filename=name)
            msg.attach(attach_msg)
        msg['Subject'] = self.subject
        msg['From'] = self.from_email
        msg['To'] = ', '.join(self.to)
        return msg.as_string()
    
    @property
    def recipients(self):
        return self.to + self.bcc

    def attach(self, name=None, content=None, mimetype=None):
        self.attachments.append((name, content, mimetype))

    def attach_file(self, path, mimetype=None):
        filename = os.path.basename(path)
        content = open(path, 'rb').read()
        self.attach(filename, content, mimetype)
        
    def mimeobject(self, type):
        if type:
            _t = 'text'
        else:
            _t = type.split('/', 1)[0]
        # TODO: we might don't need non-mutipart?
        typedict = {'text': MIMEText,
                    'application': MIMEMessage,
                    'audio': MIMEAudio,
                    'image': MIMEImage,
                    'message': MIMEMessage,
                    'video': MIMEAudio,
                    }
        return typedict.get(_t, MIMEText)
        
        
class SMTPConnection(object):
    """ A wrapper that manages the SMTP network connection."""
    def __init__(self, host, port, username, password, use_tls=False):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.use_tls = use_tls
        self.connection = None
        
    def login(self):
        if self.connection:
            return 
        self.connection = smtplib.SMTP(self.host, self.port)
        if self.use_tls:
            self.connection.ehlo()
            self.connection.starttls()
            self.connection.ehlo()
        if self.username and self.password:
            self.connection.login(self.username, self.password)

    def quit(self):
        """ Closes the connection to the email server."""
        try:
            try:
                self.connection.quit()
            except socket.sslerror:
                # This happens when calling quit() on a TLS connection
                # sometimes.
                self.connection.close()
        finally:
            self.connection = None

    def send(self, email_message):
        """ Sends one EmailMessage object"""
        if not self.connection:
            raise Exception("SMTP has connected?")
        self.connection.sendmail(email_message.from_email,
                                 email_message.recipients,
                                 email_message.message)


def send_email(subject, body, from_email, to_list, attachments=[]):
    msg = EmailMessage(subject, body, from_email, to_list)
    for attachment in attachments:
        msg.attach_file(attachment)
    smtp = SMTPConnection('smtp.gmail.com', 587, 'autotestbe@gmail.com', 'bearth1313', True)
    smtp.login()
    smtp.send(msg)
    smtp.quit()
